var express = require('express');
var router = express.Router();
var db = require('../db');
var moment = require('moment');
const random = require('string-random');

/* GET users listing. */
router.post('/register', function(req, res, next) {
    let nickname = req.body.nickname;
    let open_id = req.body.open_id;

    db.query("select count(*) as count from user where open_id = ? ", [open_id], (error, result) => {
        if(error) throw error
        console.log(result[0])
        if(result[0].count > 0){
            return res.send({code : 1, message : '账号已存在'});
        }
        let now = moment().format('YYYY-MM-DD HH:mm:ss');
        let token = random(45);
        db.query('insert into user(nickname, token, open_id, created_at, updated_at) values(?,?,?,?,?)', [nickname, token, open_id, now, now], (error, result) => {
            if(error) throw error
            console.log(result)
            if(result.insertId > 0){
                return res.send({code : 0, result : {user_id : result.insertId, token : token}});
            }else{
                return res.send({code : 1, message : '系统异常，请联系客服人员'});
            }
        });
    });
});

router.post('/login', function(req, res, next) {
    let nickname = req.body.nickname;
    let open_id = req.body.open_id;

    db.query("select count(*) as count from user where open_id = ? ", [open_id], (error, result) => {
        if(error) throw error
        console.log(result[0])
        if(result[0].count > 0){
            return res.send({code : 1, message : '账号已存在'});
        }
        let now = moment().format('YYYY-MM-DD HH:mm:ss');
        let token = random(45);
        db.query('insert into user(nickname, token, open_id, created_at, updated_at) values(?,?,?,?,?)', [nickname, token, open_id, now, now], (error, result) => {
            if(error) throw error
            console.log(result)
            if(result.insertId > 0){
                return res.send({code : 0, result : {user_id : result.insertId, token : token}});
            }else{
                return res.send({code : 1, message : '系统异常，请联系客服人员'});
            }
        });
    });
});

module.exports = router;
